package db

import (
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	Log "iot-base/auth/logger"
	config2 "iot-base/common/config"
	"iot-base/common/dbconn"
	"strings"
)

var Db *gorm.DB

func init() {
	//调用公共模块的db
	Db = dbconn.DBConnection
	//conn()
	//sqlDB, err := Db.DB()
	//if err != nil {
	//	Log.Log.Error("Db init err", err)
	//}
	//// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	//sqlDB.SetMaxIdleConns(5)
	//// SetMaxOpenConns 设置打开数据库连接的最大数量。
	//sqlDB.SetMaxOpenConns(5)
	//// SetConnMaxLifetime 设置了连接可复用的最大时间。
	//sqlDB.SetConnMaxLifetime(time.Minute * time.Duration(30))
}

func conn() {
	dbAddr := strings.Split(config2.DBOption.DBAddr, ":")
	var err error

	if config2.DBOption.Type == "postgres" {
		dsn := "host=%v port=%v user=%v password=%v sslmode=disable TimeZone=Asia/Shanghai"
		Db, err = gorm.Open(postgres.Open(fmt.Sprintf(dsn, dbAddr[0], dbAddr[1], config2.DBOption.UserName, config2.DBOption.Password)))
		if err != nil {
			Log.Log.Error("Db init err", err)
		} else {
			err = Db.Exec("Create Database " + config2.DBOption.DBName + " with owner=postgres").Error
			if err != nil {
				Log.Log.Error("Db init err", err)
			}
			dsn = "host=%v port=%v user=%v password=%v dbname=%v sslmode=disable TimeZone=Asia/Shanghai"
			Db, err = gorm.Open(postgres.Open(fmt.Sprintf(dsn, dbAddr[0], dbAddr[1],
				config2.DBOption.UserName, config2.DBOption.Password, config2.DBOption.DBName)))
			if err != nil {
				Log.Log.Error("Db init err", err)
			}
		}

	} else {
		Db, err = gorm.Open(sqlite.Open("gorm.db"))

	}
	if err != nil {
		Log.Log.Error("Db init err", err)
	}
}
